import Vue from "vue";
import Router from "vue-router";
import store from "~/store";
import NProgress from "nprogress";
import storeInit from "~/core/bootstrap/store.init";
import SystemManageRoute from "~/router/system-manage.route";
import OutsourceManageRoute from "~/router/outsource-manage.route";
import CancellationManagement from "~/router/cancellation-management.route";
import CoUrgingManagement from "~/router/co-urging-management.route";
import DashboardRoute from "./dashboard.route";
import { Message } from "element-ui";
const Login = () => import("~/pages/login.vue");
const NotFound = () => import("~/pages/not-found.vue");

import TelephoneCollectionManageRoute from "~/router/telephone-collection-manage.route";
import VisitCollectionManageRoute from "~/router/visit-collection-manage.route";
import LegalCollectionManageRoute from '~/router/legal-collection-manage.route';
import CaseImportRoute from "~/router/case-import.route";
import CustomerLitigationRoute from "~/router/customer-litigation.route";
import TempleteManage from "~/router/template-manage.route";
import ApprovalManage from "~/router/approval-manage.route";
import AssistManage from "~/router/assist-manage.route";
import CommonCasespoolManage from "~/router/common-casespool-manage.route";
import CaseVerifyManage from "~/router/case-verify-manage.route";
import LabelingStrategyConfig from "~/router/labeling-strategy-config.route";
import SynthesizeQuery from "~/router/synthesize-query.route";
import ReportManage from "~/router/report-manage.route";
import SmartCollection from "~/router/smart-collection.route";
import ResourceManage from "~/router/resouce-manage.route";
import AssistStay from "~/router/assist-stay.route";
import AssistFraud from "~/router/assist-fraud.route";
import OuterStay from "~/router/outer-stay.route";
import OuterSettle from "~/router/outer-settle.route";
import CarManagement from "./car-management.route";
import QueueManage from "~/router/queue-manage.route"
import LitigationManagement from "~/router/litigation-management.route"
import StrategicManage from "~/router/strategic-manage.route"
import RobotManageRoute from "~/router/robot-manage.route";

import CustomerGroupManagement from '~/router/customer-group-management.route'
NProgress.configure({ showSpinner: false });

//2018-09-26 催收执行页测试路由，用完删除
const CollectionExecution = () =>
  import("~/pages/collection-execution/collection-execution.vue");


Vue.use(Router);

// 生成路由配置
const routes = [
  {
    path: "/",
    name: "login",
    component: Login
  },
  //2018-09-26 催收执行页测试路由，用完删除
  {
    path: "/collection-execution/:debt?",
    name: "collection-execution",
    component: CollectionExecution,
    props: true
  },
  ...LabelingStrategyConfig,
  ...CaseVerifyManage,
  ...CommonCasespoolManage,
  ...CaseImportRoute,
  ...CustomerLitigationRoute,
  ...SystemManageRoute,
  ...DashboardRoute,
  ...OutsourceManageRoute,
  ...CancellationManagement,
  ...CoUrgingManagement,
  ...TelephoneCollectionManageRoute,
  ...LegalCollectionManageRoute,
  ...VisitCollectionManageRoute,
  ...TempleteManage,
  ...ApprovalManage,
  ...AssistManage,
  ...SynthesizeQuery,
  ...ReportManage,
  ...SmartCollection,
  ...ResourceManage,
  ...AssistStay,
  ...AssistFraud,
  ...OuterStay,
  ...OuterSettle,
  ...CarManagement,
  ...CustomerGroupManagement,
  ...QueueManage,
  ...LitigationManagement,
  ...StrategicManage,
  ...RobotManageRoute,
  // 有路由在这里添加
  {
    path: "*",
    name: "not-found",
    component: NotFound
  }
];

// 生成路由实体
const router = new Router({
  mode: "history",
  routes
});

router.openCaseDetail = (caseId, detailOptions) => {
  console.log('detailOptions',detailOptions)
  store.dispatch("collection-execution/setCollectionData", {
    caseId,
    detailOptions
  });

  store.commit("call-center/updateCallId", '');
  // 打开催收执行页面
  return router.push("/collection-execution");
};

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (to.path === "/") {
    await store.dispatch("clearUserLoginData");
  }

  if (store.state.tokenExpire && to.path !== "/") {
    // 重置用户过期状态
    store.commit("updateTokenExpire", false);
    Message.info("用户登录过期,请重新登录");
    next("/");
    NProgress.done();
  }

  if (!store.state.ready) {
    await storeInit({
      store,
      router
    });
  }

  next();
  NProgress.done();
});

/**
 * 路由前置守卫
 * 权限检测
 */
router.beforeResolve(({ matched, path }, from, next) => {
  const component = getComponent(matched);
  if (component && authCheck(component)) {
    next("/404");
  } else {
    next();
  }
});

/**
 * 路由后置守卫
 * 布局检测
 */
router.afterEach((to, from) => {
  //  布局检测
  layoutCheck(to.matched);
});

function authCheck(component) {
  const auth = component["$auth"];
//   console.log('auth', auth)
  if (auth) {
    const target = store.state.menuResource.find(
      x => Number.parseInt(x.id) === Number.parseInt(auth) || auth < 0
    );
//     console.log('target', target)
    return !target;
  }
}


// 布局监测
function layoutCheck(matched) {
  const component = getComponent(matched);
  if (component) {
    const targetLayout = component["$layout"] || "default";
    if (store.state.layout !== targetLayout) {
      store.commit("updateLayout", targetLayout);
    }
  }
}

function getComponent(matched) {
  if (matched && matched.length > 0) {
    const [{ components }] = matched;
    return components.default;
  }
}

console.log('router', router);

export default router;
